package com.tigerlee.candle.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.tigerlee.candle.activity.ChatActivity;
import com.tigerlee.candle.util.Constants;

public class ChatClientService{
	private String html = "";
	private Handler mMsgHandler;
	private Handler mHandlerThread;
	private Context mContext;

	private Socket socket;
	private String name;
	// The streams we communicate to the server; these come
	// from the socket
	private DataOutputStream dout;
	private DataInputStream din;

	private Thread checkUpdate = new Thread() {
		public void run() {
			try {
				String line = null;
				if(Constants.LOG_VISIBLE) Log.w("ChattingStart", "Start Thread");
				while (line == null) {
					Log.w("Chatting is running", "chatting is running");
					line = din.readUTF();
					html = line;
					mHandlerThread.post(showUpdate);
					line = null;
				}
			} catch (Exception e) {
			}
		}
	};
	private Runnable showUpdate = new Runnable() {
		public void run() {

            // Send the obtained bytes to the UI Activity
			mMsgHandler.obtainMessage(ChatActivity.MESSAGE_READ, html).sendToTarget();
			/*
			Message msg = mMsgHandler.obtainMessage(F1Activity.MESSAGE_TOAST);
	        Bundle bundle = new Bundle();
	        bundle.putString(F1Activity.TOAST, "Device connection was lost");
	        msg.setData(bundle);
	        mMsgHandler.sendMessage(msg);
	        */
		}
	};

	public ChatClientService(Context context, Handler handler) {
		// TODO Auto-generated constructor stub
		mContext = context;
		mMsgHandler = handler;
		mHandlerThread = new Handler();
	}

	public boolean setSocket(String ip, int port) throws IOException {
		try {
			socket = new Socket(ip, port);
			din = new DataInputStream(socket.getInputStream());
			dout = new DataOutputStream(socket.getOutputStream());
		} catch (IOException e) {
			System.out.println(e);
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public boolean connectServer(int port) {		
		try {
			if(setSocket(Constants.mChatServerIP, port) == false){
				return false;
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return false;
		}
		checkUpdate.start();
		return true;
	}
	
	public void disconnectServer() {
		try {
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void write(String msg){
		try {
			dout.writeUTF(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}